<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<%
    //以斜杠开始的相对路径找资源是以服务器路径为准，需要加上工程路径
    request.setAttribute("s_path", request.getContextPath());
%>
<head>
    <title>员工列表</title>
    <script type="text/javascript" src="${s_path}/static/js/jquery-1.12.4.min.js"></script>
    <link rel="stylesheet" href="${s_path}/static/bootstrap-3.4.1-dist/css/bootstrap.min.css">
    <script type="text/javascript" src="${s_path}/static/bootstrap-3.4.1-dist/js/bootstrap.min.js"></script>
</head>
<body>
<%--显示员工信息--%>
<div class="container">
    <div class="row">
        <div class="col-md-12 col-md-offset-1">
            <h1>SSM-CRUD</h1>
        </div>
    </div>
    <div class="row">
        <div class="col-md-12 col-md-offset-9">
            <button class="btn btn-primary" id="add">新增</button>
            <button class="btn btn-danger" id="deleteAll">删除</button>
        </div>
    </div>
    <div class="row">
        <div class="col-md-10 col-md-offset-1">
            <table class="table table-hover" id="emps_tb">
                <thead>
                <tr>
                    <th><input type="checkbox" id="checkAll"></th>
                    <th>#</th>
                    <th>lastName</th>
                    <th>email</th>
                    <th>gender</th>
                    <th>deptName</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody></tbody>
            </table>
        </div>
    </div>
    <div class="row">
        <%--分页信息--%>
        <div class="col-md-4 col-md-offset-1" id="page_info">
        </div>
        <%--分页导航栏--%>
        <div class="col-md-6" id="page_nav">
        </div>
    </div>
</div>
<!-- 添加员工模态框 -->
<div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="addModalLabel">添加员工</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal" id="addForm">
                    <div class="form-group">
                        <label class="col-sm-2 control-label">lastName</label>
                        <div class="col-sm-10">
                            <input type="text" name="lastName" class="form-control" id="inputLastName" placeholder="lastName">
                            <span id="helpBlock-name" class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">email</label>
                        <div class="col-sm-10">
                            <input type="email" name="email" class="form-control" id="inputEmail" placeholder="email">
                            <span id="helpBlock-email" class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">gender</label>
                        <div class="col-sm-10">
                            <label class="radio-inline">
                                <input type="radio" name="gender" id="radioGender1" value="0"> 男
                            </label>
                            <label class="radio-inline">
                                <input type="radio" name="gender" id="radioGender2" value="1"> 女
                            </label>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">dept</label>
                        <div class="col-sm-3">
                            <select class="form-control" name="dId">
                            </select>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="save-emp-btn">保存</button>
            </div>
        </div>
    </div>
</div>
<!-- 修改员工模态框 -->
<div class="modal fade" id="updateModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="updateModalLabel">添加员工</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal" id="updateForm">
                    <div class="form-group">
                        <label class="col-sm-2 control-label">lastName</label>
                        <div class="col-sm-10">
                            <p class="form-control-static" id="update-lastName"></p>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">email</label>
                        <div class="col-sm-10">
                            <input type="email" name="email" class="form-control" id="inputUpdateEmail" placeholder="email">
                            <span id="helpBlock-update-email" class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">gender</label>
                        <div class="col-sm-10">
                            <label class="radio-inline">
                                <input type="radio" name="gender" id="radioGender1-update" value="0"> 男
                            </label>
                            <label class="radio-inline">
                                <input type="radio" name="gender" id="radioGender2-update" value="1"> 女
                            </label>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">dept</label>
                        <div class="col-sm-3">
                            <select class="form-control" name="dId">
                            </select>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="update-emp-btn">更新</button>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript">
    //页面加载完成后通过ajax获取分页数据
    $(function () {
        to_page(1);

    });
    //给添加员工按钮绑定单击事件打开模态框
    $("#add").click(function () {
        resetForm("#addForm")
        getDepts("#addForm select")
        $("#addModal").modal({
            backdrop:"static"
        })
    })
    //给编辑按钮 动态 绑定单击事件打开模态框
    $(document).on("click","button[name='edit-btn']",function () {
        //查询并绑定部门信息
        getDepts("#updateForm select")
        //查询并绑定员工信息
        getUpdateEmp(this)
        $("#updateModal").modal({
            backdrop:"static"
        })
    })
    //添加员工校验用户名
    $("#inputLastName").blur(function () {
        var empName = this.value;
        var regxName = /(^[a-zA-Z0-9_-]{6,16}$)|(^[\u2E80-\u9FFF]{2,5})/;
        if (!regxName.test(empName)){
            show_validate_msg("#inputLastName","error","用户名应为6-16位英文或2-5位中文")
        }else{
            show_validate_msg("#inputLastName","success","用户名可用")
            //后台校验用户名是否存在
            $.getJSON("${s_path}/isexist","lastName="+empName,function (exist) {
                if (exist){
                    show_validate_msg("#inputLastName","error","用户名已存在")
                    $("#save-emp-btn").attr("ajax-addEmp","error")
                }else {
                    $("#save-emp-btn").attr("ajax-addEmp","success")
                }
            })
        }
    })
    //添加员工校验邮箱
    $("#inputEmail").blur(function () {
        var empEmail = this.value;
        var regxEmail = /^[a-z\d]+(\.[a-z\d]+)*@([\da-z](-[\da-z])?)+(\.{1,2}[a-z]+)+$/;
        if (!regxEmail.test(empEmail)){
            show_validate_msg("#inputEmail","error","邮箱格式错误")
        }else{
            show_validate_msg("#inputEmail","success","")
            //后台校验邮箱是否已被注册
            $.getJSON("${s_path}/isexist","email="+empEmail,function (exist) {
                if (exist){
                    show_validate_msg("#inputEmail","error","该邮箱已被注册")
                    $("#save-emp-btn").attr("ajax-addEmp","error")
                }else {
                    $("#save-emp-btn").attr("ajax-addEmp","success")
                }
            })
        }
    })
    //编辑员工校验邮箱
    $("#inputUpdateEmail").blur(function () {
        var empEmail = this.value;
        var regxEmail = /^[a-z\d]+(\.[a-z\d]+)*@([\da-z](-[\da-z])?)+(\.{1,2}[a-z]+)+$/;
        if (!regxEmail.test(empEmail)){
            show_validate_msg("#inputUpdateEmail","error","邮箱格式错误")
        }else{
            show_validate_msg("#inputUpdateEmail","success","")
            //后台校验邮箱是否已被注册
            $.getJSON("${s_path}/isexist","email="+empEmail,function (exist) {
                if (exist){
                    show_validate_msg("#inputUpdateEmail","error","该邮箱已被注册")
                    $("#update-emp-btn").attr("ajax-updateEmp","error")
                }else {
                    $("#update-emp-btn").attr("ajax-updateEmp","success")
                }
            })
        }
    })
    //添加员工
    $("#save-emp-btn").click(function () {
        var attr = $(this).attr("ajax-addEmp");
        if ("success"==attr){
            $.post("${s_path}/addEmp",$("#addForm").serialize(),function (result) {
                if (result.code==100){
                    //关闭模态框
                    $("#addModal").modal('hide')
                    //添加成功，查询最后一页
                    to_page(totalEmp)
                }else if (result.code == 200) {
                    if (undefined!=result.extend.errorFields.lastName){
                        show_validate_msg("#inputLastName","error",result.extend.errorFields.lastName)
                    }
                    if (undefined!=result.extend.errorFields.email){
                        show_validate_msg("#inputEmail","error",result.extend.errorFields.email)
                    }
                }
            })
        }
    })
    //更新员工
    $("#update-emp-btn").click(function () {
        var eid = $(this).attr("edit-emp-id")
        $.ajax({
            url:"${s_path}/updateEmp",
            data:$("#updateForm").serialize()+"&id="+eid,
            type:"put",
            success:function (data) {
                //更新完成关闭模态框
                $("#updateModal").modal("hide")
                //跳转至更新前页码
                to_page(currentPn)
            }
        })
    })
    //删除一个员工
    $(document).on("click","button[name='delete-btn']",function () {
        var lastName = $(this).parent().parent().find("td:eq(2)").text()
        var id = $(this).parent().parent().find("td:eq(1)").text()
        if (confirm("确定删除【"+lastName+"】吗")){
            $.ajax({
                url:"${s_path}/deleteEmp/"+id,
                type:"DELETE",
                success:function (data) {
                    to_page(currentPn)
                }
            })
        }
    })
    //单个复选框单击事件 name=checkItem
    $(document).on("click","input[name='checkItem']",function () {
        //与点击前状态相反
        //alert(this.checked)
        this.checked = this.checked;
        //如果当前选中复选框数量等于当前页面复选框数量，则给 checkAll 添加选中状态
        var checkedCount = $(":checkbox[name=checkItem]:checked").length
        var checkboxCount = $(":checkbox[name=checkItem]").length
        $("#checkAll").prop("checked",checkedCount == checkboxCount)
    })
    //全选复选框单击事件 id=checkAll
    $("#checkAll").click(function () {
        $(":checkbox[name=checkItem]").prop("checked",this.checked)
    })
    //删除选中员工
    $("#deleteAll").click(function () {
        var checkedEmps = $(":checkbox[name=checkItem]:checked")
        var ids = "";
        var lastNames = "";
        $.each(checkedEmps,function () {
            ids += $(this).parent().parent().find("td:eq(1)").text()+"-"
            lastNames += $(this).parent().parent().find("td:eq(2)").text()+","
        })
        ids = ids.substr(0,lastNames.length-1)
        lastNames = lastNames.substr(0,lastNames.length-1)
        if (confirm("确定删除【"+lastNames+"】吗？")){
            $.ajax({
                url:"${s_path}/deleteEmp/"+ids,
                type:"DELETE",
                success:function () {
                    $("#checkAll").prop("checked",false)
                    to_page(currentPn)
                }
            })
        }
    })
    //编辑员工信息绑定
    function getUpdateEmp(element){
        $.ajax({
            url:"${s_path}/getEmp/"+$(element).parent().parent().find("td:eq(1)").text(),
            type:"get",
            success:function (result) {
                var emp = result.extend.emp
                $("#update-lastName").text(emp.lastName)
                $("#inputUpdateEmail").val(emp.email)
                $("#updateForm input[name='gender']").val([emp.gender])
                $("#updateForm select").val(emp.dId)
                $("#update-emp-btn").attr("edit-emp-id",emp.id);
            }
        })
    }
    //显示校验结果
    function show_validate_msg(element,status,msg){
        //先清除之前的校验样式和信息
        $(element).parent().removeClass("has-success has-error")
        $(element).next("span").text("")
        if ("success"==status){
            $(element).parent().addClass("has-success")

        }else{
            $(element).parent().addClass("has-error")
        }
        $(element).next("span").text(msg)
    }
    //清空表单样式及内容
    function resetForm(element){
        $(element)[0].reset()
        $(element).find("*").removeClass("has-error has-success")
        $(element).find(".help-block").text("")
    }
    //获取所有的部门信息并绑定数据
    function getDepts(element){
        //清空之前下拉列表的值
        $(element).empty();
        $.ajax({
            url:"${s_path}/depts",
            type:"get",
            success:function (result) {
                $.each(result.extend.depts,function () {
                    $(element).append($("<option></option>").append(this.deptName).attr("value",this.id))
                })

            }
        })
    }
    function to_page(pn) {
        $.ajax({
            url: "${s_path}/emps",
            data: "pn=" + pn,
            type: "get",
            success: function (result) {
                //加载分页数据
                buildEmps(result);
                //加载分页信息
                buildPageInfo(result);
                //加载分页导航栏
                buildPageNav(result);
            }
        });
    }

    function buildEmps(result) {
        $("#emps_tb tbody").empty()
        var emps = result.extend.pageInfo.list;
        $.each(emps, function (index, item) {
            var td_cbox = $("<td><input type='checkbox' name='checkItem'/></td>")
            var td_id = $("<td></td>").append(item.id);
            var td_lastName = $("<td></td>").append(item.lastName);
            var td_email = $("<td></td>").append(item.email);
            var td_gender = $("<td></td>").append(item.gender == 0 ? '男' : '女');
            var td_deptName = $("<td></td>").append(item.dept.deptName);

            var edit = $("<button name='edit-btn'></button>").addClass("btn btn-primary btn-sm")
                .append("<span></span>").addClass("glyphicon glyphicon-pencil")
                .append("编辑");
            var rm = $("<button name='delete-btn'></button>").addClass("btn btn-danger btn-sm")
                .append("<span></span>").addClass("glyphicon glyphicon-trash")
                .append("删除");
            var td_btn = $("<td></td>").append(edit).append(" ").append(rm);

            $("<tr></tr>")
                .append(td_cbox)
                .append(td_id).append(td_lastName).append(td_email).append(td_gender).append(td_deptName).append(td_btn)
                .appendTo("#emps_tb tbody");
        })
    }
    //声明全局总记录数供其他功能使用
    var totalEmp,currentPn;
    function buildPageInfo(result) {
        $("#page_info").empty()
        var page_info = $("#page_info");
        page_info.append("当前第")
        var pageNum = $("<span></span>").addClass("label label-default").append(result.extend.pageInfo.pageNum)
        page_info.append(pageNum).append("页，共有")
        var pages = $("<span></span>").addClass("label label-default").append(result.extend.pageInfo.pages)
        page_info.append(pages).append("页，总计")
        var total = $("<span></span>").addClass("label label-default").append(result.extend.pageInfo.total)
        page_info.append(total).append("条记录")
        totalEmp = result.extend.pageInfo.total;
        currentPn = result.extend.pageInfo.pageNum;
    }

    function buildPageNav(result) {
        $("#page_nav").empty()
        var ul = $("<ul></ul>").addClass("pagination")

        var first_page = $("<li></li>").append($("<a></a>").append("首页").attr("href","#")).click(function () {
            to_page(1)
        })
        ul.append(first_page)
        //如果存在上一页
        if(result.extend.pageInfo.hasPreviousPage){
            var prev_page = $("<li></li>").append($("<a></a>").append("&laquo;").attr("href","#")).click(function () {
                to_page(result.extend.pageInfo.pageNum-1)
            })
            ul.append(prev_page)
        }

        $.each(result.extend.pageInfo.navigatepageNums,function (index, item) {
            var pn = $("<li></li>").append($("<a></a>").append(item).attr("href","#"))
            if (item == result.extend.pageInfo.pageNum) {
                pn.addClass("active")
            }else {
                pn.click(function () {
                    to_page(item)
                })
            }
            ul.append(pn)
        })
        //如果存在下一页
        if(result.extend.pageInfo.hasNextPage){
            var next_page = $("<li></li>").append($("<a></a>").append("&raquo;").attr("href","#")).click(function () {
                to_page(result.extend.pageInfo.pageNum+1)
            })
            ul.append(next_page)
        }
        var last_page = $("<li></li>").append($("<a></a>").append("尾页").attr("href","#")).click(function () {
            to_page(result.extend.pageInfo.pages)
        })
        ul.append(last_page)

        $("<nav></nav>").append(ul).appendTo("#page_nav")

    }
</script>
</body>
</html>
